package user03.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import user03.mapper.TRoleMenuMapper;
import user03.model.TRoleMenu;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TRoleMenuService extends ServiceImpl<TRoleMenuMapper, TRoleMenu> {

    public List<Long> selectMenuIdsByRoleId(List<Long> roleIds) {
        if (roleIds == null || roleIds.size() <= 0) {
            return null;
        }
        QueryWrapper<TRoleMenu> wrapper = new QueryWrapper<>();
        wrapper.in("t_role_id", roleIds);
        List<TRoleMenu> list = list(wrapper);
        if (list == null || list.size() <= 0) {
            return null;
        }
        List<Long> menuIds = new ArrayList<>();
        for (TRoleMenu tRoleMenu : list) {
            menuIds.add(tRoleMenu.getTMenuId());
        }
        return menuIds;
    }

    public Boolean updateRoleMenus(Long roleId, List<Long> menuIds) {
        Boolean delete = deleteByRoleId(roleId);
        if (delete != null && delete) {
            List<TRoleMenu> roleMenus = new ArrayList<>();
            for (Long menuId : menuIds) {
                TRoleMenu roleMenu = new TRoleMenu();
                roleMenu.setTRoleId(roleId);
                roleMenu.setTMenuId(menuId);
                roleMenus.add(roleMenu);
            }
            return saveBatch(roleMenus);
        }
        return false;
    }

    private Boolean deleteByRoleId(Long roleId) {
        UpdateWrapper<TRoleMenu> wrapper = new UpdateWrapper<>();
        wrapper.eq("t_role_id", roleId);
        return remove(wrapper);
    }
}
